package ah.szxy.service.impl;

import ah.szxy.domain.OrderTbl;
import ah.szxy.mapper.OrderTblMapper;
import ah.szxy.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单操作实现
 *
 * @author caohaiyang
 * @create 2020-09-17 下午 04:10
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderTblMapper orderTblMapper;

    @Autowired
    private AccountServiceApi accountServiceApi;

    public static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Transactional
    @Override
    public OrderTbl createOrder(String userId, String productNo, int count) {
        log.info("开始创建订单, 用户为{} ,商品为{} , 数量为{} ",userId, productNo, count);
        //1.扣减用户的余额  account-service - rpc
        int money=productNo.equals("HUAWEI_0001")?2000:productNo.equals("XIAOMI_002")?1000:9999;//因为库存表没有商品的价格
        ResponseEntity<Void> responseEntity = accountServiceApi.debit(userId, money);
        if (responseEntity.getStatusCode()!= HttpStatus.OK){
            throw new RuntimeException("远程扣减运费失败");
        }
        //2.写本地的订单列表
        OrderTbl orderTbl = OrderTbl.builder().userId(userId).commodityCode(productNo).count(count).build();
        int insert = orderTblMapper.insert(orderTbl);
        System.out.println("是否成功: "+insert);
        //成功后打印到日志中去
        log.info("订单创建成功, 用户为{} ,商品为{} , 数量为{} ",userId, productNo, count);
        return orderTbl;
    }


}